package com.ndkj.blog.utils;

import com.ndkj.blog.constant.BlogConstant;
import com.ndkj.blog.constant.MailConstant;
import com.ndkj.blog.constant.SafeLocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @program: blog
 * @description: 后台登录归属地校验，若不是常用归属地，那么发出邮件告警
 * @author: liuyong
 * @create: 2022-05-05 17:52
 */
@Slf4j(topic = "com.blog.LoginUserCheck")
@Component
public class LoginUserCheck {

    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private SafeLocation safeLocation;

    public void adminLoginAttributionCheck() {
        String ip = RequestUtils.getIpAddr();
        String response = null;
        try{
            //请求api得到的json回复
            response = new GetAttribution().sendGet(BlogConstant.Attribution.URL + ip + "&json=true");
        } catch (IOException e) {
            log.error("获取当前管理员归属地时发生异常");
        }
        boolean flag = false;
        if (StringUtils.isNotBlank(response)) {
            for (String adminLocation : safeLocation.getCommonlyUsedAttribution()) {
                // 一般来说，这个循环内必定有一定contains值为true
                boolean contains = response.contains(adminLocation);
                // 只要出现了一次true，此时flag就为true
                flag = flag || contains;
            }
            if (!flag) {
                mailUtils.sendMail("博客登录告警通知", "您在" + TimeFormatUtils.TimeParse(new Date()) +
                        "在非常用地区[" +response.substring(response.indexOf("\"addr\":\"") + 8, response.indexOf("\",\"regionNames\""))+ "]登录，如是本人操作请忽略此通知。",
                        MailConstant.MAIL_RECEIVE_ADDRESS);
            }
        }

    }

}
